/*
 * @Author: linxun 
 * @Date: 2021-03-04 20:23:20 
 * @Last Modified by: linxun
 * @Last Modified time: 2021-07-23 15:26:10
 * @Description: 数据集列表
 */

import React, { Fragment } from 'react';
import { useIntl, history } from 'umi';
import { Table, Divider, Popconfirm, Tag, Button, Tooltip, Badge } from 'antd';
import moment from 'moment';
import { getText } from '../util';
import { TIMEFORMAT, ADHUB_PREFIX } from '@/utils/const';
import { AuthzHOC } from '@apulis/authz';

import styles from '../index.less';

export const statusColorConfig = {
  'labeled': '#2db7f5',
  'unlabeled': '#f50',
  'labeling': '#87d068',
  'initialized': '#999',
  'creating': '#87d068',
  'success': '#2db7f5',
  'publishing': '#87d068',
  'failed': '#f50',
  'adding': '#87d068',
  'submitting': '#87d068',
};
const canDeleteStatus = ['failed', 'initialized', 'success'];

const ListTable = props => {
  const { formatMessage } = useIntl();
  const {
    tableData,
    onDelete,
    onSorterChange,
    onPageChage,
    expandedRowRender,
    onExpand,
    loading,
    onRelease,
    onEditClick,
    onDetailClick,
    curTab, // 1-原始数据集 2-已发布数据集
    onProcessing,
    isPublic,
    labelTypes,
    labelScenes,
    labelStatus,
    listSourceType,
    createStatus,
    onAnnotClick,
  } = props;

  const toSamples = record => {
    const option = `${record.annotStatus === 'unlabeled' ? 1 : 0}`;
    history.push({
      pathname: `/${isPublic ? 'public' : 'QIP'}/dataManage/dataSet/samples/${record.id}`,
      state: {
        record,
        option,
        annotType: record.annotType,
      },
      query: {
        option,
        annotType: record.annotType,
      }
    });
  };

  const columns = [{
    title: formatMessage({ id: 'dataSet.dataSet.table.name' }),
    dataIndex: 'name',
    fixed: 'left',
    width: 250,
    render: (text, record) => (
      <div style={{ wordWrap: 'break-word', wordBreak: 'break-word' }}>
        {curTab === '1' ? <a onClick={() => onDetailClick(record)}>{text}</a> : text}
      </div>
    ),
  }, {
    title: formatMessage({ id: 'dataSet.dataSet.table.labelScenes' }),
    dataIndex: 'annotScene',
    render: text => getText(labelScenes, text),
  }, {
    title: formatMessage({ id: 'dataSet.dataSet.table.labelType' }),
    dataIndex: 'annotType',
    render: text => getText(labelTypes, text),
  }, {
    title: formatMessage({ id: 'dataSet.dataSet.table.dataType' }),
    dataIndex: 'cvDatasetFormat',
  }, {
    title: formatMessage({ id: 'dataSet.table.createdAt' }),
    dataIndex: 'createdAt',
    // sorter: true,
    render: text => moment(text).format(TIMEFORMAT),
  }, {
    title: formatMessage({ id: 'dataSet.table.updatedAt' }),
    dataIndex: 'updatedAt',
    sorter: true,
    render: text => moment(text).format(TIMEFORMAT),
  }];

  if (curTab === '1') {
    columns.splice(4, 0, {
      title: formatMessage({ id: 'dataSet.dataSet.table.sourceType' }),
      dataIndex: 'sourceType',
      render: text => getText(listSourceType, text),
    }, {
      title: formatMessage({ id: 'dataSet.dataSet.table.samplesNum' }),
      dataIndex: 'itemCount',
    }, {
      title: formatMessage({ id: 'dataSet.dataSet.table.label' }),
      dataIndex: 'labelList',
      render: text => text?.length > 3 ? <Tooltip title={text?.join('，')}>{text?.slice(0, 3)?.join('，')}，...</Tooltip> : text?.join('，'),
    }, {
      title: formatMessage({ id: 'dataSet.dataSet.table.status' }),
      dataIndex: 'annotStatus',
      render: text => <Tag color={statusColorConfig[text]}>{getText(labelStatus, text)}</Tag>,
    }, {
      title: formatMessage({ id: 'dataSet.dataSet.table.createStatus' }),
      dataIndex: 'status',
      render: text => <Fragment><Badge color={statusColorConfig[text]} />{getText(createStatus, text)}</Fragment>,
    });
    columns.push({
      title: formatMessage({ id: 'dataSet.table.option' }),
      dataIndex: 'option',
      align: 'right',
      fixed: 'right',
      render: (_, record) => {
        const canCutoutAnnotTypes = ['object_detection', 'ocr_detection'];
        const canAnnot = record.status === 'success';
        const canCutout = record.annotStatus === 'labeled'
          && record.sourceType !== 'make_from_cutout'
          && canCutoutAnnotTypes.includes(record.annotType)
          && record.status === 'success';
        const canPublish = record.status === 'success'
          && record.annotStatus === 'labeled';
        const canDelete = record.annotStatus !== 'labeling'
          && canDeleteStatus.includes(record.status);

        return (
          <Fragment>
            <a
              className={canAnnot ? '' : styles.disabled}
              onClick={() => {
                if (canAnnot) {
                  toSamples(record);
                }
              }}
            >
              {formatMessage({ id: 'dataSet.dataSet.table.option.samples' })}
            </a>
            <Divider type='vertical' />
            <Fragment>
              <Tooltip title={canCutout ? '' : '数据集创建成功，数据全部标注完成，数据源是非扣图来源且标注类型为【物体检测】和【文本检测】才能执行此操作'}>
                <a
                  className={canCutout ? '' : styles.disabled}
                  onClick={() => {
                    if (canCutout) {
                      onProcessing(record);
                    }
                  }}
                >
                  {formatMessage({ id: 'dataSet.dataSet.table.option.processing' })}
                </a>
                <Divider type='vertical' />
              </Tooltip>
            </Fragment>
            <a
              className={canAnnot ? '' : styles.disabled}
              onClick={() => {
                if (canAnnot) {
                  onAnnotClick(record);
                }
              }}
            >标注</a>
            <Divider type='vertical' />
            <Tooltip title={canPublish ? '' : '数据集创建成功并且数据全部标注才能发布'}>
              <a
                onClick={() => {
                  if (canPublish) {
                    onRelease(record);
                  }
                }}
                className={canPublish ? '' : styles.disabled}
              >
                {formatMessage({ id: 'dataSet.dataSet.table.option.release' })}
              </a>
            </Tooltip>
            <AuthzHOC anyOf={[
              [ADHUB_PREFIX + '/ad-hub/cv_datasets', 'delete'],
              [ADHUB_PREFIX + '/ad-hub/cv_datasets/id/{id}', 'delete'],
            ]}>
              <Fragment>
                <Divider type='vertical' />
                {canDelete ?
                  <Popconfirm
                    title={formatMessage(
                      { id: 'dataSet.table.option.delete.confirm' },
                      { name: record.name }
                    )}
                    placement='topRight'
                    onConfirm={() => onDelete(record)}
                  >
                    <a className={styles.dangerText}>
                      {formatMessage({ id: 'dataSet.table.option.delete' })}
                    </a>
                  </Popconfirm> :
                  <Tooltip title='当前数据集状态不能删除'>
                    <a className={`${styles.dangerText} ${styles.disabled}`}>
                      {formatMessage({ id: 'dataSet.table.option.delete' })}
                    </a>
                  </Tooltip>
                }
              </Fragment>
            </AuthzHOC>
          </Fragment >
        )
      }
    });
  }
  if (curTab === '2') {
    columns.splice(1, 0, {
      title: formatMessage({ id: 'dataSet.dataSet.table.lastestVersion' }),
      dataIndex: 'version',
      // sorter: true,
    }, {
      title: formatMessage({ id: 'dataSet.dataSet.table.versionNum' }),
      dataIndex: 'versionCount',
      // sorter: true,
    });
    columns.push({
      title: formatMessage({ id: 'dataSet.table.option' }),
      dataIndex: 'option',
      align: 'right',
      fixed: 'right',
      render: (_, record) => (
        <Fragment>
          <AuthzHOC anyOf={[
            [ADHUB_PREFIX + '/ad-hub/cv_datasets', 'delete'],
            [ADHUB_PREFIX + '/ad-hub/cv_datasets/id/{id}', 'delete'],
          ]}>
            <Popconfirm
              title={<div style={{ maxWidth: 250 }}>删除已发布数据集可能会导致关联该数据集的任务运行失败，请确认是否删除？</div>}
              placement='topRight'
              onConfirm={() => onDelete(record, true)}
              okText='确认删除'
            >
              <a className={styles.dangerText}>
                {formatMessage({ id: 'dataSet.table.option.delete' })}
              </a>
            </Popconfirm>
          </AuthzHOC>
        </Fragment>
      )
    });
  }

  return (
    <Table
      dataSource={tableData.list}
      pagination={{
        ...tableData.pagination,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total) => `${formatMessage({ id: 'dataSet.table.total' }, { total })}`,
        onChange: onPageChage,
        onShowSizeChange: onPageChage,
      }}
      loading={loading}
      rowKey='id'
      columns={columns}
      onChange={onSorterChange}
      expandable={curTab === '2' ? {
        rowExpandable: () => true,
        onExpand,
        expandedRowRender,
      } : false}
      scroll={tableData.list && tableData.list.length ? { x: 'max-content' } : {}}
    />
  )
}

export default ListTable;